<template>
    <div id="app">
        <div class="container">
            <!-- 左侧面板 -->
            <div class="left-panel">
                <div class="batch-input">
                    <label>批次号：</label>
                    <input ref="batchInput" v-model="batchNumber" type="text" placeholder="请输入批次号"
                           class="batch-input-field" :disabled="isMeasuring">
                    <button @click="startMeasurement" :disabled="!batchNumber.trim() || isMeasuring"
                            class="start-button">
                        开始测量
                    </button>
                </div>

                <div class="select-group">
                    <label>选择检验员：</label>
                    <select v-model="inspector" :disabled="isMeasuring">
                        <option v-for="(inspectorOption, index) in inspectorOptions" :key="index" :value="inspectorOption">
                            {{ inspectorOption }}
                        </option>
                    </select>
                    <label>选择模式：</label>
                    <select v-model="mode" :disabled="isMeasuring">
                        <option v-for="(modeOption, index) in modeOptions" :key="index" :value="modeOption">
                            {{ modeOption }}
                        </option>
                    </select>
                </div>

                <textarea ref="dataInput" v-model="inputText" placeholder="输入数据（回车自动保存）" style="width: 782px; height: 70px;"
                          @keyup.enter="handleEnter" @input="handleInput"></textarea>

                <div class="button-group">
                    <button @click="exportData" :disabled="!isMeasuring" class="save-button">
                        保存数据
                    </button>
                    <button @click="clearAll" :disabled="!isMeasuring" class="clear-button">
                        清空数据
                    </button>
                    <button @click="deleteSelected" :disabled="!selectedItem ||!isMeasuring"
                            class="delete-button">
                        删除选中数据
                    </button>
                </div>
            </div>

            <!-- 右侧面板 -->
            <div class="right-panel">
                <table>
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>内容</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(item, index) in dataList" :key="item.id" @click="selectItem(item)"
                        :class="{ 'selected-row': selectedItem?.id === item.id }">
                        <td>{{ index + 1 }}</td>
                        <td class="content-cell" :style="{ color: getTextColor(item.content) }">{{ item.content }}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div id="chart">
            <h2>数据统计分析</h2>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import XLSX from 'xlsx';
import fs from 'fs';
import path from 'path';

export default {
    data() {
        return {
            batchNumber: '',
            inputText: '',
            dataList: [],
            selectedItem: null,
            nextId: 1,
            isMeasuring: false,
            chart: null,
            inspector: '',
            inspectorOptions: ['马惠玲', '肖士营', '贺青青', '赵小松', '霍娟', '潘秀杰', '覃燕芳', '余贺燕', '朱雅娟', '杜江艳', '许利艳', '秦琳', '王亚楠',"于淼"],
            mode: '',
            modeOptions: ['EXCEL', 'MES'],
            baogong_state: false,
            max_value: 0,
            min_value: 0,
            order_name_id:0,
            inspector_id:0,
        };
    },
    mounted() {
        this.inspector = this.inspectorOptions[0];
        this.mode = this.modeOptions[0];
        this.chart = echarts.init(document.getElementById('chart'));
        this.updateChart();
    },
    watch: {
        dataList: {
            handler() {
                this.updateChart();
            },
            deep: true
        }
    },
    methods: {
        startMeasurement() {
            var order_name = this.batchNumber;
            console.log(order_name)
            if (order_name.includes("@")) {
                alert("有@!!!")
            } else {
                // 这里需要替换为实际的 HTTP 请求库，如 Axios
                this.http.get('api/table_wgjy/gzd_search', { name_order: order_name }).then((reslut) => {
                    console.log("GGGGG", reslut);
                    if (reslut == 0) {
                        alert("未报工！！！")
                        this.$refs.batchInput.style.backgroundColor = "red"
                        this.baogong_state = false
                        if (this.batchNumber.trim()) {
                            this.isMeasuring = true;
                            this.$refs.dataInput.focus();
                        }
                    } else {
                        this.order_name_id = reslut["rows"][0]["id"]
                        console.log(reslut["rows"][0]);
                        var result_final = reslut["rows"][0];
                        if (result_final["state"] == "draft") {
                            if (result_final["judgement"] == false) {
                                if (this.batchNumber.trim()) {
                                    this.isMeasuring = true;
                                    this.$refs.dataInput.focus();
                                }
                                this.$refs.batchInput.style.backgroundColor = "green"
                                this.baogong_state = true
                                if (result_final["value_max"] == 0 || result_final["value_min"] == false) {
                                    if (result_final["value_min"] != 0) {
                                        this.max_value = 1000
                                        this.min_value = result_final["value_min"]
                                    } else {
                                        this.max_value = 0
                                        this.min_value = 0
                                    }
                                } else if (result_final["value_max"] == 0 && result_final["value_min"] == 0) {
                                    this.max_value = result_final["value_max"]
                                    this.min_value = result_final["value_min"]
                                } else if (result_final["value_max"] == false && result_final["value_min"] == false) {
                                    this.max_value = 0
                                    this.min_value = 0
                                } else {
                                    this.max_value = result_final["value_max"]
                                    this.min_value = result_final["value_min"]
                                }
                            }
                        } else {
                            alert("重复！！")
                            this.baogong_state = false
                        }
                    }

                }).catch((error) => {
                    console.error('同步失败:', error);
                });
            }
        },
        clearAll() {
            this.dataList = [];
            this.inputText = '';
            this.selectedItem = null;
            this.batchNumber = '';
            this.isMeasuring = false;
            this.inspector = '';
            this.mode = '';
            this.updateChart();
            this.$refs.batchInput.style.backgroundColor = null;
            this.inspector = this.inspectorOptions[0];
            this.mode = this.modeOptions[0];
        },
        exportData() {
            var order_name = this.inspector;
            console.log(order_name)
            this.http.get('api/table_wgjy/gzd_data_deal', { name_order: order_name,order_id:this.order_name_id }).then((reslut) => {
                    console.log("GGGGG", reslut);                  

                }).catch((error) => {
                    console.error('同步失败:', error);
                });

            const workbook = XLSX.utils.book_new();

            // 创建工作表
            const worksheet = XLSX.utils.aoa_to_sheet([
                ['项目', '值'],
                ['批次号', this.batchNumber],
                ['检验员', this.inspector],
                ['数据内容', '']
            ]);


            // 准备表格数据
            const tableData = this.dataList.map((item, index) => ({ 序号: index + 1, 内容: item.content }));
            // 从第 5 行开始添加表格数据
            XLSX.utils.sheet_add_json(worksheet, tableData, { origin: 'A5', skipHeader: true });

            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet, '数据');

            // 生成文件名
            const currentTime = new Date().toISOString().replace(/:/g, '-').split('.')[0];
            const fileName = `光泽度 ${this.batchNumber} ${currentTime} ${this.inspector}.xlsx`;

            // 生成文件路径
            const filePath = '\\\\10.7.1.22\\品管部\\品管部存储文件\\多功能测试\\2025' + '\\' + fileName;

            try {
                const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
                // 在浏览器中无法直接使用 fs.writeFileSync，需要使用其他方式保存文件，比如借助下载工具
                // 这里简单展示为下载文件
                const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                a.click();
                URL.revokeObjectURL(url);
                alert('数据已成功保存为 Excel 文件');
            } catch (error) {
                console.error('保存 Excel 文件失败:', error);
                alert('保存 Excel 文件失败，请检查路径和权限');
            }
        },
        selectItem(item) {
            this.selectedItem = this.selectedItem?.id === item.id ? null : item;
        },
        deleteSelected() {
            if (!this.selectedItem) return;
            const index = this.dataList.findIndex(
                item => item.id === this.selectedItem.id
            );
            if (index !== -1) {
                this.dataList.splice(index, 1);
                this.selectedItem = null;
            }
        },
        handleEnter(event) {
            event.preventDefault();
            this.saveToTable();
        },
        handleInput(event) {
            if (event.inputType === 'insertLineBreak') {
                this.inputText = this.inputText.replace(/\n/g, '');
            }
        },
        saveToTable() {
            const content = this.inputText
               .trim()
               .replace(/\n/g, ' ');

            if (content) {
                this.dataList.push({
                    id: this.nextId++,
                    content: content
                });
                this.inputText = '';
            }
        },
        updateChart() {
            const xData = this.dataList.map((item, index) => `序号 ${index + 1}`);
            const yData = this.dataList.map(item => parseFloat(item.content) || 0);

            // 生成另外两条曲线的数据
            const yData2 = Array.from({ length: xData.length }, () => this.max_value);
            const yData3 = Array.from({ length: xData.length }, () => this.min_value);

            const option = {
                title: {
                    text: "数据统计分析"
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['测量值', '最大值', '最小值']
                },
                xAxis: {
                    type: 'category',
                    data: xData
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        data: yData,
                        type: 'line',
                        name: '测量值',
                        label: {
                            show: true,
                            position: 'top'
                        }
                    },
                    {
                        data: yData2,
                        type: 'line',
                        name: '最大值',
                        label: {
                            show: true,
                            position: 'top'
                        }
                    },
                    {
                        data: yData3,
                        type: 'line',
                        name: '最小值',
                        label: {
                            show: true,
                            position: 'top'
                        }
                    }
                ]
            };
            this.chart.setOption(option);
        },
        getTextColor(content) {
            const value = parseFloat(content);
            if (!isNaN(value) && value >= this.min_value && value <= this.max_value) {
                return 'green';
            }
            return 'red';
        }
    }
};
</script>

<style scoped>
.batch-input {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 20px;
}

.batch-input label {
    white-space: nowrap;
    font-weight: bold;
    color: #333;
}

.batch-input-field {
    flex: 1;
    padding: 10px;
    border: 2px solid #42b983;
    border-radius: 4px;
    font-size: 14px;
    transition: all 0.3s;
}

.batch-input-field:disabled {
    background-color: #f5f5f5;
    border-color: #cccccc;
}

.start-button {
    padding: 10px 20px;
    background-color: #2196F3;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.start-button:disabled {
    background-color: #90CAF9;
    cursor: not-allowed;
}

.start-button:not(:disabled):hover {
    background-color: #1976D2;
}

.save-button {
    background-color: #4CAF50;
}

.save-button:disabled {
    background-color: #A5D6A7;
    cursor: not-allowed;
}

.button-group button:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
}

.button-group button:not(:disabled):hover {
    filter: brightness(0.9);
}

.button-group {
    display: flex;
    gap: 30px;
    flex-wrap: wrap;
}

.clear-button:not(:disabled) {
    background-color: #dc1a1a;
}

.selected-row {
    background-color: #e3f2fd !important;
    cursor: pointer;
}

tr {
    transition: background-color 0.2s;
}

tr:hover {
    background-color: #f5f5f5;
}

.container {
    display: flex;
    height: 35vh;
    padding: 20px;
    padding-right: auto;
    background-color: #f5f5f5;
}

.left-panel {
    flex: 1;
    padding-right: 20px;
    border-right: 2px solid #e0e0e0;
}

.right-panel {
    flex: 1;
    padding-left: 20px;
    /* 添加滚动属性 */
    overflow-y: auto;
}

textarea {
    width: 100%;
    height: 150px;
    padding: 12px;
    border: 2px solid #42b983;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.3s;
}

button {
    padding: 10px 20px;
    color: rgb(17, 2, 2);
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

table {
    width: 100%;
    border-collapse: collapse;
    background-color: white;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

th,
td {
    border: 1px solid #e0e0e0;
    padding: 12px;
    text-align: left;
}

.content-cell {
    white-space: pre-line;
    max-width: 400px;
    word-break: break-word;
}

#chart {
    height: 50vh;
}

.select-group {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 10px;
}

.select-group label {
    white-space: nowrap;
    font-weight: bold;
    color: #333;
}

.select-group select {
    padding: 8px;
    border: 2px solid #42b983;
    border-radius: 4px;
    font-size: 14px;
    transition: all 0.3s;
}

.select-group select:disabled {
    background-color: #f5f5f5;
    border-color: #cccccc;
}
</style>